import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/execute_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/role_personnel_entity.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

///特殊作业-自定义人员选择样式控件
///[title] 标题
///[onCallBack] 选择回调
///[dataList] 已有的数据列表
///[isRequired] 是否必填
///[hintText] 提示文字
///[operatorType] 人员类型 作业人类型 0：作业实施人 1：作业负责人 2：监护人 3:编制人 4：司索人 5:指挥人 6：用电人 7：安全交底人 8：接受交底人 9：验收人
///[isEnabled] 是否可编辑
///[isShowCertificateNumber] 是否显示证件编号
///[queryParameters] 请求人员数据的参数
class CustomSelectWorkUserPage extends StatefulWidget {
  const CustomSelectWorkUserPage({
    required this.title,
    required this.onCallBack,
    this.dataList,
    this.isRequired = true,
    super.key,
    this.hintText,
    this.operatorType,
    this.isEnabled = true,
    this.isShowCertificateNumber = true,
    this.queryParameters = const {},
  });

  final String title;
  final Function(List<ExecuteTicketReceiptListOperatorLists>) onCallBack;
  final List<ExecuteTicketReceiptListOperatorLists>? dataList;
  final bool isRequired;
  final String? hintText;
  final int? operatorType;
  final bool isEnabled;
  final bool isShowCertificateNumber;
  final Map<String, dynamic> queryParameters;

  @override
  State<CustomSelectWorkUserPage> createState() => _CustomSelectWorkUserPageState();
}

class _CustomSelectWorkUserPageState extends State<CustomSelectWorkUserPage> {
  List<ExecuteTicketReceiptListOperatorLists> dateList = [];

  @override
  initState() {
    super.initState();
    _initDate();
  }

  /// 初始化数据
  void _initDate() {
    //添加数据
    if (widget.dataList != null && widget.dataList!.isNotEmpty) {
      dateList = widget.dataList!;
    }
    //是否包含指定人员
    bool haveOperator = false;
    for (var item in dateList) {
      if (item.operatorType == (widget.operatorType ?? 0)) {
        haveOperator = true;
        break;
      }
    }
    //如果为空则添加一个空数据
    if (dateList.isEmpty || !haveOperator) {
      dateList.add(ExecuteTicketReceiptListOperatorLists()..operatorType = (widget.operatorType ?? 0));
    }
    setState(() {});
  }

  ///获取作业人信息
  Widget _getOperatorView(ExecuteTicketReceiptListOperatorLists item, int index) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 7.w),
      padding: EdgeInsets.symmetric(horizontal: 18.w, vertical: 14.w),
      decoration: BoxDecoration(
        color: const Color(0xFFF7F7F7),
        borderRadius: BorderRadius.circular(8.w),
      ),
      child: Column(
        children: [
          //人员选择
          _getPersonnelSelection(item, index),
          AppGaps.vGap10,
          //签名逻辑
          _getSignatureView(item, index),
          //获取作业编号显示
          _getCertificateNumberView(item, index),
        ],
      ),
    );
  }

  ///获取人员选择样式
  Widget _getPersonnelSelection(ExecuteTicketReceiptListOperatorLists item, int index) {
    return Row(
      children: [
        Text(
          '*',
          style: TextStyle(
            fontSize: 14.sp,
            height: 1.2,
            color: AppColors.meaning_color_danger,
          ),
        ),
        Text(
          widget.title,
          style: TextStyle(
            fontSize: 14.sp,
            height: 1.1,
            color: AppColors.font_color_black,
          ),
        ),
        AppGaps.hGap20,
        Expanded(
            child: item.operatorUserName!.isNotEmpty
                ? Text(
                    item.operatorUserName ?? '',
                    textAlign: TextAlign.end,
                    style: TextStyle(
                      fontSize: 14.sp,
                      height: 1.2,
                      color: const Color(0xFF262F38),
                    ),
                  )
                : Text(
                    widget.isEnabled ? widget.hintText ?? '请选择' : '暂无',
                    textAlign: TextAlign.end,
                    style: TextStyle(
                      fontSize: 14.sp,
                      height: 1.2,
                      color: AppColors.text_grey,
                    ),
                  )),
        Visibility(
            visible: widget.isEnabled,
            child: Row(
              children: [AppGaps.hGap6, Icon(Icons.arrow_forward_ios, size: 14.sp, color: AppColors.text_grey)],
            )),
      ],
    ).clickOnce(() {
      FocusScope.of(context).unfocus();
      if (!widget.isEnabled) {
        return;
      }
      Get.toNamed(AppRoutes.personnelSelection, arguments: {
        'queryParameters': widget.queryParameters,
        'isRadio': true,
      })?.then((value) {
        //如果不为空则设置人员信息
        if (value != null) {
          final List<RolePersonnelEntity> personList = value as List<RolePersonnelEntity>;
          item.operatorUserId = personList[0].getId();
          item.operatorUserName = personList[0].getShowName();
          item.operatorType = widget.operatorType ?? 0;
          _callBack();
          setState(() {});
        }
      });
    });
  }

  ///获取签名样式
  Widget _getSignatureView(ExecuteTicketReceiptListOperatorLists item, int index) {
    return Container(
      alignment: Alignment.center,
      height: 36.w,
      decoration: BoxDecoration(
        color: const Color(0xffF7F7FB),
        borderRadius: BorderRadius.all(Radius.circular(4.w)),
        border: Border.all(width: 1.w, color: const Color(0xffEBEDF0)),
      ),
      child: item.operatorUserSign!.isEmpty
          ? Text('点击此处签名',
              style: TextStyle(
                fontSize: 14.sp,
                height: 1.2,
                color: AppColors.font_color_gray,
              ))
          : Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4.w),
                  color: Colors.white,
                  image: DecorationImage(
                    image: NetworkImage(Interface.fileUrl + item.operatorUserSign!),
                  )),
            ),
    ).clickOnce(() {
      FocusScope.of(context).unfocus();
      if (!widget.isEnabled && item.number != 1) {
        return;
      }
      //如果没有选择人员
      if (item.operatorUserName!.isEmpty) {
        AppToast.showWarning('请先选择人员');
        return;
      }
      Get.toNamed(AppRoutes.signature)?.then((value) {
        //如果不为空则设置签名
        if (value != null) {
          setState(() {
            item.operatorUserSign = value.toString();
            item.number = 0;
          });
        }
        _callBack();
      });
    });
  }

  ///获取证书编号显示
  Widget _getCertificateNumberView(ExecuteTicketReceiptListOperatorLists item, int index) {
    return Visibility(
        visible: widget.isShowCertificateNumber,
        child: Column(
          children: [
            AppGaps.vGap16,
            Divider(
              height: 1.w,
              color: const Color(0xFFE6E7EB),
            ),
            AppGaps.vGap12,
            Row(
              children: [
                // Text(
                //   '*',
                //   style: TextStyle(
                //     fontSize: 14.sp,
                //     height: 1.2,
                //     color: AppColors.meaning_color_danger,
                //   ),
                // ),
                Text(
                  '证书编号',
                  style: TextStyle(
                    fontSize: 14.sp,
                    height: 1.1,
                    color: AppColors.font_color_black,
                  ),
                ),
                // Expanded(
                //     child: Text(
                //   item.operatorCertificateId ?? '',
                //   // '2515454541215',
                //   textAlign: TextAlign.end,
                //   style: TextStyle(
                //     fontSize: 14.sp,
                //     height: 1.2,
                //     color: const Color(0xFF5C6DFF),
                //   ),
                // )),
                // 输入证书编号
                Expanded(
                    child: TextField(
                  enabled: widget.isEnabled,
                  controller: TextEditingController.fromValue(TextEditingValue(
                    text: item.operatorCertificateId ?? '',
                  )),
                  textInputAction: TextInputAction.done,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: const Color(0xFF5C6DFF),
                    fontWeight: FontWeight.w400,
                  ),
                  textAlign: TextAlign.right,
                  maxLines: null,
                  decoration: InputDecoration(
                    isCollapsed: true,
                    border: const OutlineInputBorder(
                      borderSide: BorderSide.none,
                    ),
                    hintText: widget.isEnabled ? '请输入' : '暂无',
                    hintStyle: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w400,
                      color: AppColors.text_grey,
                    ),
                  ),
                  onChanged: (value) {
                    item.operatorCertificateId = value;
                  },
                )),
              ],
            ),
          ],
        ));
  }

  ///回调给外部
  void _callBack() {
    widget.onCallBack(dateList);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.w),
      ),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 17.w, vertical: 12.w),
            child: Row(
              children: [
                SvgPicture.asset(
                  AppImages.icon_title,
                  width: 20.w,
                  height: 20.w,
                ),
                AppGaps.hGap6,
                Text(
                  '${widget.title}信息',
                  style: TextStyle(color: const Color(0xff262F38), height: 1.2, fontWeight: FontWeight.w500, fontSize: 14.sp),
                ),
                const Spacer(),
                Visibility(
                    visible: widget.isEnabled,
                    child: Text(
                      '添加人员',
                      style: TextStyle(color: const Color(0xff5C6DFF), height: 1.2, fontWeight: FontWeight.w400, fontSize: 12.sp),
                    ).clickOnce(() {
                      dateList.add(ExecuteTicketReceiptListOperatorLists()..operatorType = widget.operatorType ?? 0);
                      AppToast.showSuccess('添加成功!');
                      setState(() {});
                    })),
              ],
            ),
          ),
          // Container(
          //   color: const Color(0xFFF5F7FC),
          //   height: 1.w,
          // ),
          ListView.separated(
            itemCount: dateList.length,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              final item = dateList[index];
              //  只显示传入的类型
              if (item.operatorType != (widget.operatorType ?? 0)) {
                return Container();
              }
              return Container(
                alignment: Alignment.center,
                child: Stack(
                  alignment: Alignment.topRight,
                  children: [
                    //获取作业人信息
                    _getOperatorView(item, index),
                    //删除按钮
                    Visibility(
                        visible: widget.isEnabled,
                        child: const Icon(
                          Icons.highlight_remove,
                          color: Color(0xFFFD6B6B),
                        ).clickOnce(() {
                          dateList.remove(item);
                          _callBack();
                          setState(() {});
                        }))
                  ],
                ),
              );
            },
            separatorBuilder: (BuildContext context, int index) {
              if (dateList[index].operatorType != (widget.operatorType ?? 0)) {
                return Container();
              }
              return AppGaps.vGap8;
            },
          ),
          AppGaps.vGap12,
        ],
      ),
    );
  }
}
